package com.hongtech.tiny.modules.gen.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongtech.tiny.common.response.PageResult;
import com.hongtech.tiny.modules.gen.mapper.GeneratorMapper;
import com.hongtech.tiny.modules.gen.utils.GenUtils;
import com.hongtech.tiny.modules.gen.vo.GenTableVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 */
@Service
@RequiredArgsConstructor
public class SysGeneratorService {

    private final GeneratorMapper generatorDao;

    public PageResult<GenTableVO> queryList(String tableName, Page<GenTableVO> page) {
        Page<GenTableVO> list = generatorDao.queryList(page, tableName);
        return PageResult.restPage(list);
    }

    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }

    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}
